// 格式化金额
export const formatPrice = (price) => {
  return `¥${Number(price).toFixed(2)}`
}

// 格式化日期时间
export const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 格式化日期
export const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化时间
export const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  return `${hour}:${minute}`
}

// 防抖函数
export const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 节流函数
export const throttle = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null) return null
  if (typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof RegExp) return new RegExp(obj)
  
  const clone = Array.isArray(obj) ? [] : {}
  Object.keys(obj).forEach(key => {
    clone[key] = deepClone(obj[key])
  })
  
  return clone
}

// 生成随机字符串
export const randomString = (length = 32) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 格式化文件大小
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`
}

// 获取文件扩展名
export const getFileExt = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
}

// 判断是否是移动设备
export const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

// 获取URL参数
export const getUrlParams = (url = window.location.href) => {
  const params = {}
  const searchParams = new URL(url).searchParams
  for (const [key, value] of searchParams) {
    params[key] = value
  }
  return params
}

// 下载文件
export const downloadFile = (url, filename) => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 复制文本到剪贴板
export const copyToClipboard = (text) => {
  return navigator.clipboard.writeText(text)
}

// 生成随机颜色
export const randomColor = () => {
  return `#${Math.floor(Math.random() * 16777215).toString(16)}`
}

// 判断是否是外部链接
export const isExternalLink = (url) => {
  return /^(https?:|mailto:|tel:)/.test(url)
}

// 格式化手机号
export const formatPhone = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 格式化银行卡号
export const formatBankCard = (card) => {
  return card.replace(/\s/g, '').replace(/(\d{4})/g, '$1 ').trim()
}

// 校验手机号
export const isValidPhone = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

// 校验邮箱
export const isValidEmail = (email) => {
  return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
}

// 校验身份证号
export const isValidIdCard = (idCard) => {
  return /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/.test(idCard)
}

// 获取图片主色调
export const getImageColor = (imageUrl) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'Anonymous'
    img.src = imageUrl
    
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      
      ctx.drawImage(img, 0, 0)
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data
      
      let r = 0, g = 0, b = 0
      
      for (let i = 0; i < imageData.length; i += 4) {
        r += imageData[i]
        g += imageData[i + 1]
        b += imageData[i + 2]
      }
      
      const pixelCount = imageData.length / 4
      const color = {
        r: Math.round(r / pixelCount),
        g: Math.round(g / pixelCount),
        b: Math.round(b / pixelCount)
      }
      
      resolve(`rgb(${color.r}, ${color.g}, ${color.b})`)
    }
    
    img.onerror = reject
  })
}

/**
 * 测试后端API连接
 * 这个函数会尝试发送一个简单请求到后端，以验证连接是否正常
 * @returns {Promise<{success: boolean, message: string, details: Object}>} 测试结果
 */
export function testBackendConnection() {
  console.log('开始测试后端API连接...');
  return new Promise((resolve) => {
    // 创建超时计时器
    const timeout = setTimeout(() => {
      resolve({
        success: false,
        message: '请求超时，后端服务可能未启动或网络问题',
        details: { error: 'timeout', timestamp: new Date().toISOString() }
      });
    }, 5000);
    
    // 使用fetch API尝试连接
    fetch('/api/ping', { 
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    })
    .then(response => {
      clearTimeout(timeout);
      if (response.ok) {
        return response.text().then(text => {
          resolve({
            success: true,
            message: '后端API连接正常',
            details: { 
              status: response.status,
              statusText: response.statusText,
              response: text,
              timestamp: new Date().toISOString()
            }
          });
        });
      } else {
        return response.text().then(text => {
          resolve({
            success: false,
            message: `HTTP错误: ${response.status} ${response.statusText}`,
            details: { 
              status: response.status, 
              statusText: response.statusText,
              response: text,
              timestamp: new Date().toISOString()
            }
          });
        }).catch(err => {
          resolve({
            success: false,
            message: `HTTP错误: ${response.status} ${response.statusText}`,
            details: { 
              status: response.status, 
              statusText: response.statusText,
              error: String(err),
              timestamp: new Date().toISOString()
            }
          });
        });
      }
    })
    .catch(error => {
      clearTimeout(timeout);
      // 尝试另一个API端点
      console.log('第一个API端点失败，尝试另一个端点...');
      fetch('/api/employee/login', { 
        method: 'OPTIONS',
        headers: { 'Content-Type': 'application/json' }
      })
      .then(response => {
        if (response.ok || response.status === 204) {
          resolve({
            success: true,
            message: '后端API连接正常(备用端点)',
            details: { 
              status: response.status,
              statusText: response.statusText,
              endpoint: '/api/employee/login',
              timestamp: new Date().toISOString()
            }
          });
        } else {
          resolve({
            success: false,
            message: `后端API连接失败: HTTP ${response.status}`,
            details: { 
              status: response.status,
              statusText: response.statusText,
              endpoint: '/api/employee/login',
              timestamp: new Date().toISOString()
            }
          });
        }
      })
      .catch(nestedError => {
        resolve({
          success: false,
          message: '所有API端点连接失败，后端服务可能未启动',
          details: { 
            error: String(error), 
            nestedError: String(nestedError),
            timestamp: new Date().toISOString()
          }
        });
      });
    });
  });
}

export default {
  formatPrice,
  formatDateTime,
  formatDate,
  formatTime,
  debounce,
  throttle,
  deepClone,
  randomString,
  formatFileSize,
  getFileExt,
  isMobile,
  getUrlParams,
  downloadFile,
  copyToClipboard,
  randomColor,
  isExternalLink,
  formatPhone,
  formatBankCard,
  isValidPhone,
  isValidEmail,
  isValidIdCard,
  getImageColor
} 